package com.gupao.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器式单例
 * 模仿Spring,
 * 有点是适用于创建实例非常多的情况，便于管理
 * 缺点是非线程安全的
 */
public class ContainerSingleton {
    private ContainerSingleton(){}
    private static Map<String, Object> ioc = new ConcurrentHashMap<String, Object>();

    public static Object getInstance(String keyName){
        synchronized(ioc){
            if(!ioc.containsKey(keyName)){
                Object obj = null;
                try {
                    obj = Class.forName(keyName);
                    ioc.put(keyName, obj);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                return obj;
            }else{
                return ioc.get(keyName);
            }
        }
    }
}
